package io.adrainty.algorithm.leetcode.lcr;

import java.util.HashMap;
import java.util.Map;

/**
 * LCR 010. 和为 K 的子数组
 * @link <a href="https://leetcode.cn/problems/QTMn0o/">...</a>
 * @author AdRainty
 * @version V1.0.0
 * @since 2024/9/8 下午7:52
 */
public class LCR010 {

    public int subarraySum(int[] nums, int k) {
        // 前缀和
        Map<Integer, Integer> preSum = new HashMap<>();
        preSum.put(0, 1);
        int sum = 0;
        int res = 0;
        for (int num : nums) {
            sum += num;
            res += preSum.getOrDefault(sum - k, 0);
            preSum.put(sum, preSum.getOrDefault(sum, 0) + 1);
        }
        return res;
    }

}
